const router = require('koa-router')()
const { ObjectID } = require('bson')
const jwt = require('jsonwebtoken')
const { MaintenanceBase, Maintenance, Inspection, Equipment } = require('../db/wang')

router.prefix('/wang')

//维保未完成
router.get('/list', async function (ctx, next) {
  let plan_name = new RegExp(ctx.query.keyword, "i")
  //对token解密
  try {
    let token = ctx.header.authorization
    token = token.split(' ')[1]
    var currentUser = jwt.verify(token, 'flag')
  } catch (err) {
    ctx.body = err
  }
  if (currentUser) {
    const data = await MaintenanceBase.find({ $and: [{ repair_id: currentUser.userid }, { plan_name }, { plan_end_time: { $gte: Date.now() } }, { maintenance_id: undefined }] })
    ctx.body = { msg: '请求成功', data, code: 200 }
  } else {
    ctx.body = { msg: '请求不存在', code: 404 }
  }
})


//维保详情
router.post('/maintenance', async function (ctx, next) {
  if (!ctx.query.id) {
    return ctx.body = { msg: '请你传递维保基本id', code: 405 }
  }
  try {
    let token = ctx.header.authorization
    token = token.split(' ')[1]
    var currentUser = jwt.verify(token, 'flag')
  } catch (err) {
    ctx.body = err
  }
  const postData = ctx.request.body
  if (currentUser) {
    try {
      let obj = { responsible_person: currentUser.userid, active_time: Date.now(), ...postData }
      const craRole = await Maintenance.create(obj)
      await MaintenanceBase.updateOne({ _id: ctx.query.id }, { $set: { maintenance_id: craRole._id } })
    } catch (err) {
      return ctx.body = err
    }
    ctx.body = { msg: '请求成功', code: 200 }
  } else {
    ctx.body = { msg: '请求不存在', code: 404 }
  }
})


//维保已完成
router.get('/active', async function (ctx, next) {
  let plan_name = new RegExp(ctx.query.keyword, "i")
  //对token解密
  try {
    let token = ctx.header.authorization
    token = token.split(' ')[1]
    var currentUser = jwt.verify(token, 'flag')
  } catch (err) {
    ctx.body = err
  }
  if (currentUser) {
    const data = await MaintenanceBase.find({ $and: [{ repair_id: currentUser.userid }, { plan_name }, { maintenance_id: { $ne: undefined } }] })
    ctx.body = { msg: '请求成功', data, code: 200 }
  } else {
    ctx.body = { msg: '请求不存在', code: 404 }
  }
})

//维保详情已完成 仔细
router.get('/script', async function (ctx, next) {
  const id = ctx.query.id
  const searchUser = await MaintenanceBase.findOne({ _id: id }).populate('maintenance_id').populate('repair_id')
  ctx.body = {
    searchUser,
    code: 200,
    msg: '获取详情成功'
  }
})


//维保统计页面

//维保未完成
router.get('/nums', async function (ctx, next) {
  //进行中
  const noAcive = await MaintenanceBase.find({ $and: [{ plan_end_time: { $gte: Date.now() } }, { maintenance_id: undefined }] })
  //已完成
  const acive = await MaintenanceBase.find({ maintenance_id: { $ne: undefined } })
  //超时的
  const longTime = await MaintenanceBase.find({ $and: [{ plan_end_time: { $lte: Date.now() } }, { maintenance_id: undefined }] })
  //过期的
  const falseTime = await MaintenanceBase.find({ $and: [{ plan_end_time: { $lte: Date.now() } }, { maintenance_id: undefined }] })
  ctx.body = { msg: '请求成功', data: [{title:'进行中',count:noAcive.length},{title:'已完成',count:acive.length},{title:'超时的',count:longTime.length},{title:'过期的',count:falseTime.length}], code: 200 }
})

//维保类型 
router.get("/cates", async (ctx, next) => {
  const groupUser = await MaintenanceBase.aggregate([{ '$group': { '_id': '$maintenance_cate', 'count': { '$sum': 1 } } }])
  ctx.body = {
    data: groupUser
  }
})

//任务情况
// router.get("/circumstance",async (ctx,next)=>{

//   ctx.body={
//     data:groupUser
//   }
// })

//待领取 巡检
router.get('/inspectionList', async function (ctx, next) {
  let InspectionName = new RegExp(ctx.query.keyword, "i")
  const data = await Inspection.find({ $and: [{ InspectionName }, { repair_id: undefined }, { Inspection_end_time: { $gte: Date.now() } }] })
  ctx.body = { msg: '请求成功', data, code: 200 }
})
//点击进行领取
router.post('/inspectionList', async function (ctx, next) {
  if (!ctx.query.id) {
    return ctx.body = {
      code: 401,
      msg: '请携带领取的id!'
    }
  }
  try {
    let token = ctx.header.authorization
    token = token.split(' ')[1]
    var currentUser = jwt.verify(token, 'flag')
  } catch (err) {
    ctx.body = err
  }
  if (currentUser) {
    await Inspection.updateOne({ _id: ctx.query.id }, { $set: { repair_id: currentUser.userid } })
    ctx.body = {
      msg: "领取成功",
      code: 200
    }
  } else {
    ctx.body = {
      msg: "领取失败。信息无效",
      code: 305
    }
  }
})
//待执行和执行中
router.get('/executed', async function (ctx, next) {
  let InspectionName = new RegExp(ctx.query.keyword, "i")
  try {
    let token = ctx.header.authorization
    token = token.split(' ')[1]
    var currentUser = jwt.verify(token, 'flag')
  } catch (err) {
    ctx.body = err
  }
  const data = await Inspection.find({ $and: [{ InspectionName }, { repair_id: currentUser.userid }, { isFinish: false }, { Inspection_end_time: { $gte: Date.now() } }] })
  ctx.body = { msg: '请求成功', data, code: 200 }
})

//巡检任务详情
router.get('/queck', async function (ctx, next) {
  const id = ctx.query.id
  if (!id) {
    return ctx.body = {
      msg: "查询的id",
      code: 305
    }
  }
  await next()
  const data =  await Equipment.aggregate([
    {$match:  
      {'inspection_id':ObjectID(id)}
    },
    {$group:{'_id':'$location',children: { $push: "$$ROOT" }}},
  ])
  ctx.body = { msg: '请求成功', data, code: 200 }
})

//查看巡检详情
router.get('/desc',async function(ctx,next){
  if (!ctx.query.id) {
    return ctx.body = {
      code: 401,
      msg: '请携带查询的的id!'
    }
  }
  try{
    const baseInfo= await Inspection.findOne({_id:ctx.query.id})
  if(!baseInfo.isFinish){
    return ctx.body = {msg:'该任务未完成！',code:200}
  }
  const itemInfo = await Equipment.find({$and:[{inspection_id:ctx.query.id},{}]})
  ctx.body = {baseInfo,itemInfo}
  }catch(err){
    ctx.body = {err}
  }
})


//查看巡检已完成的
router.get('/completed',async function(ctx,next){
  let InspectionName = new RegExp(ctx.query.keyword, "i")
  try {
    let token = ctx.header.authorization
    token = token.split(' ')[1]
    var currentUser = jwt.verify(token, 'flag')
    const data = await Inspection.find({$and:[{ InspectionName },{repair_id:currentUser.userid},{isFinish:true}]})
    ctx.body = {data,msg:"获取成功！",code:200}
  } catch (err) {
    ctx.body = err
  }
})


//巡检处理提交
router.post('/commit',async function(ctx,next){
  let data = ctx.request.body
  if(!(data.length)){
    return ctx.body = {msg:'提交内容不能为空！',code:304}
  }else{
    const id=  data[0].inspection_id
    await Inspection.updateOne({_id:id},{$set:{isFinish:true}})
  }
  try{
    data.forEach(async(item)=>{
      await Equipment.updateOne({_id:item._id},{$set:{...item}})
    })
    ctx.body = {msg:'提交成功',code:200}
  }catch(err){
   return ctx.body = err 
  }
})

//巡检group
router.get('/InspectionGroup',async function(ctx,next){
  //待处理
  const awaitTask = await Inspection.find({$and:[{Inspection_end_time:{$lte:Date.now()}},{isFinish:false},{repair_id:undefined}]})
  //处理中
  const processingTask = await Inspection.find({$and:[{repair_id:{$ne:undefined}},{isFinish:false},{Inspection_end_time:{$lte:Date.now()}}]})
  //已完成
  const activeTask = await Inspection.find({isFinish:true})
  //已过期
  const falseTask = await Inspection.find({$and:[{isFinish:false},{Inspection_end_time:{$gte:Date.now()}}]})
  ctx.body = [{title:'待处理任务',count:awaitTask.length},{title:'处理中任务',count:processingTask.length},{title:'已完成任务',count:activeTask.length},{title:'已过期任务',count:falseTask.length}]
})
module.exports = router
